package NIO;

import org.junit.Test;

import javax.naming.directory.SearchResult;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.time.LocalDateTime;
import java.util.Date;
import java.util.Iterator;

/**
 * @author VX5
 * @Title: MJC
 * @ProjectName DataStructure
 * @Description: TODO
 * @date ${DAT}16:40
 */
public class TestNonBlockingNIO {
    //客户端
    @Test
    public void client() throws IOException {
        SocketChannel sChannel = SocketChannel.open(new InetSocketAddress("127.0.0.1",9898));

        //切换非阻塞缓存区
        sChannel.configureBlocking(false);

        //分配指定大小的分配区
        ByteBuffer buf = ByteBuffer.allocate(1024);

        //发送时间给服务器
        buf.put(LocalDateTime.now().toString().getBytes());
        buf.flip();
        sChannel.write(buf);
        buf.clear();

        //关闭通道
        sChannel.close();
    }

    @Test
    public void server() throws IOException {
        //获取通道
        ServerSocketChannel ssChannel = ServerSocketChannel.open();

        //切换非阻塞模式
        ssChannel.configureBlocking(false);

        //绑定连接
        ssChannel.bind(new InetSocketAddress(9898));

        //获取选择器
        Selector selector = Selector.open();

        //将通道注册到选择器
        ssChannel.register(selector, SelectionKey.OP_ACCEPT);//监听接受事件

        //轮询式的获取选择器上已经准备就绪的事件
        while (selector.select() > 0){

            //获取当前选择器中所有注册的“选择键”
            Iterator<SelectionKey> it = selector.selectedKeys().iterator();

            //迭代获取
            while (it.hasNext()){
                //准备获取准备就绪的事件
                SelectionKey sk = it.next();

                //判断具体是什么事件
                if (sk.isAcceptable()){
                    //若接受就绪，获取客户端连接
                    SocketChannel socketChannel = ssChannel.accept();

                    //切换非阻塞模式
                    socketChannel.configureBlocking(false);

                    //将该通道注册到选择器上
                    socketChannel.register(selector,SelectionKey.OP_READ);
                }else if (sk.isReadable()){//读就绪状态
                    SocketChannel sChannel = (SocketChannel) sk.channel();

                    //读取数据
                    ByteBuffer buffer = ByteBuffer.allocate(1024);

                    int len = 0;
                    while ((len = sChannel.read(buffer)) > 0){
                        buffer.flip();
                        System.out.println(new String(buffer.array(),0,len));
                        buffer.clear();
                    }
                }

                //取消选择键 SelectKey
                it.remove();
            }
        }
    }
}
